<template>
  <div class="admin-dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">用户总数</div>
          <div class="stat-value">{{ userCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">试卷总数</div>
          <div class="stat-value">{{ examCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">答卷总数</div>
          <div class="stat-value">{{ answerCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">今日新增答卷</div>
          <div class="stat-value">{{ todayCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="16">
        <el-card>
          <div slot="header" class="clearfix">
            <span>答卷数据分析</span>
            <el-radio-group v-model="chartTimeRange" size="small" style="float: right;">

            </el-radio-group>
          </div>
          <div id="answerChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div slot="header" class="clearfix">
            <span>最近答卷</span>
          </div>
          <el-table :data="recentAnswers" stripe style="width: 100%">
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="title" label="试卷名称"></el-table-column>
            <el-table-column prop="score" label="得分"></el-table-column>
            <el-table-column label="提交时间">
              <template #default="scope">
                {{ formatDate(scope.row.submitTime) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import * as echarts from "echarts";

export default {
  name: 'AdminDashboard',
  data() {
    return {
      userCount: 0,
      examCount: 0,
      answerCount: 0,
      todayCount: 0,
      recentAnswers: [],
      chartTimeRange: 'week', // 默认显示近7天数据
      chartInstance: null,
      chartData: {
        dailyCounts: [], // 每日答卷数量
        dailyScore: [], // 平均分
        dates: [] // 日期列表
      }
    }
  },
  mounted() {
    this.fetchData();
    this.initChart();
    // 监听窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.resizeChart);

    // 释放 ECharts 实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    // 获取数据的方法
    fetchData() {
      // 获取统计数据的接口
      this.$http.get('/api/getStatsData')
          .then(response => {
            const data = response.data;
            this.userCount = data.data.userCount;
            this.examCount = data.data.examCount;
            this.answerCount = data.data.answerCount;
            this.todayCount = data.data.todayAnswerCount;
          })
          .catch(error => {
            console.error('获取统计数据失败:', error);
          });

      // 获取最近答卷数据的接口
      this.$http.get('/api/getRecentAnswerData')
          .then(response => {
            this.recentAnswers = response.data.data;
            this.processChartData(); // 处理图表数据
            this.updateChart(); // 更新图表
          })
          .catch(error => {
            console.error('获取最近答卷数据失败:', error);
          });

    },
    // 处理图表数据（新增方法）
    processChartData() {
      // 如果没有答卷数据，直接返回
      if (!this.recentAnswers || this.recentAnswers.length === 0) {
        this.chartData = {
          dailyCounts: [],
          averageScores: [],
          dates: []
        };
        return;
      }

      // 根据选择的时间范围过滤数据
      const timeRangeDays = {
        'week': 7,
        'month': 30,
        'quarter': 90
      };

      const days = timeRangeDays[this.chartTimeRange];
      const now = new Date();
      const startTime = new Date(now);
      startTime.setDate(now.getDate() - days);

      // 过滤指定时间范围内的答卷
      const filteredAnswers = this.recentAnswers.filter(answer => {
        const submitDate = new Date(answer.submitTime);
        return submitDate >= startTime && submitDate <= now;
      });

      // 按日期分组并计算每日统计数据
      const dailyData = {};

      filteredAnswers.forEach(answer => {
        const submitDate = new Date(answer.submitTime);
        // 格式化为 YYYY-MM-DD
        const dateKey = `${submitDate.getFullYear()}-${(submitDate.getMonth() + 1).toString().padStart(2, '0')}-${submitDate.getDate().toString().padStart(2, '0')}`;

        if (!dailyData[dateKey]) {
          dailyData[dateKey] = {
            count: 0,
            totalScore: 0,
            scores: []
          };
        }

        dailyData[dateKey].count++;
        dailyData[dateKey].totalScore += answer.score;
        dailyData[dateKey].scores.push(answer.score);
      });

      // 转换为图表所需格式
      const dates = Object.keys(dailyData).sort();
      const dailyCounts = dates.map(date => dailyData[date].count);
      const averageScores = dates.map(date => {
        const data = dailyData[date];
        return data.count > 0 ? data.totalScore / data.count : 0;
      });

      this.chartData = {
        dates,
        dailyCounts,
        averageScores
      };
    },
    initChart() {
      // ECharts初始化代码
      const chartDom = document.getElementById('answerChart');
      this.chartInstance = echarts.init(chartDom);
      // 设置图表配置项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['答卷数量', '平均分']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.dates
        },
        yAxis: [
          {
            type: 'value',
            name: '答卷数量',
            min: 0,
            interval: 5,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '平均分',
            min: 0,
            max: 100,
            axisLabel: {
              formatter: '{value} 分'
            }
          }
        ],
        series: [
          {
            name: '答卷数量',
            type: 'bar',
            data: this.chartData.dailyCounts
          },
          {
            name: '平均分',
            type: 'line',
            yAxisIndex: 1,
            data: this.chartData.averageScores,
            itemStyle: {
              color: '#f56c6c'
            }
          }
        ]
      };

      // 使用配置项显示图表
      this.chartInstance.setOption(option);
    },

    updateChart() {
      if (!this.chartInstance) return;

      const option = {
        xAxis: {
          data: this.chartData.dates
        },
        series: [
          {
            data: this.chartData.dailyCounts
          },
          {
            data: this.chartData.averageScores
          }
        ]
      };

      this.chartInstance.setOption(option);
    },
    // 调整图表尺寸
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    // 切换时间范围
    handleTimeRangeChange() {
      this.processChartData(); // 重新处理数据
      this.updateChart(); // 更新图表
    },
    formatDate(timeStr) {
      // 格式化日期的方法
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  }
}
</script>